package com.lyl.jingdongsearch.service;

import com.alibaba.fastjson.JSON;
import com.lyl.jingdongsearch.config.HtmlParseUtil;
import com.lyl.jingdongsearch.domain.Content;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lylbell
 * @date 2021-09-26 16:09
 */
@Service
public class ContentServiceImpl {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 解析content，存入es中
     * @param keyword
     * @return
     */
    public Boolean parseContent(String keyword) throws IOException {
        //1、根据关键字获取解析的content
        List<Content> contents = new HtmlParseUtil().parseJD(keyword);
        //2、批量加入到es中
        BulkRequest bulkRequest = new BulkRequest();

        //1)设置超时时间
        bulkRequest.timeout("2m");

        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_index")
                .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }
    /**
     * 分页查找数据
     * @param keyword
     * @param page
     * @param size
     * @return
     */
    public List<Map<String,Object>> searchContent(String keyword, int page, int size) throws IOException {
        if (page <= 1) {
            page = 1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_index");

        //搜索构造器
        SearchSourceBuilder builder = new SearchSourceBuilder();

        //分页
        builder.from(page);
        builder.size(size);

        //精准查找
        TermQueryBuilder titleTerm = QueryBuilders.termQuery("title", keyword);
        builder.query(titleTerm);
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索
        searchRequest.source(builder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }

    /**
     * 高亮查找数据
     * @param keyword
     * @param page
     * @param size
     * @return
     */
    public List<Map<String,Object>> searchHigLightContent(String keyword, int page, int size) throws IOException {
        if (page <= 1) {
            page = 1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_index");

        //搜索构造器
        SearchSourceBuilder builder = new SearchSourceBuilder();

        //分页
        builder.from(page);
        builder.size(size);

        //精准查找
        TermQueryBuilder titleTerm = QueryBuilders.termQuery("title", keyword);
        builder.query(titleTerm);
//        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮查找
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);  //多个高亮显示
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        builder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(builder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            //原来的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (title != null) {
                Text[] fragments =
                        title.fragments();
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;
                }
                sourceAsMap.put("title",n_title);
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}
